package com.hyacinth.cloudnote.modules.note.service;

import com.hyacinth.cloudnote.common.exception.ExceptionHolder;
import com.hyacinth.cloudnote.modules.note.model.Note;
import com.hyacinth.cloudnote.modules.note.model.NoteBook;
import com.hyacinth.cloudnote.modules.note.repository.NoteBookRepository;
import com.hyacinth.cloudnote.modules.note.repository.NoteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.UUID;

import static com.hyacinth.cloudnote.modules.common.errorcode.NoteErrorCode.E1000000001;
import static com.hyacinth.cloudnote.modules.common.errorcode.NoteErrorCode.E1000002001;

/**
 * NoteBook实体对应的业务逻辑Service实现类
 * @author zhangfb
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class NoteBookService {

    @Autowired
    private NoteBookRepository noteBookRepository;
    @Autowired
    private NoteRepository noteRepository;
    @Autowired
    private FavoriteService favoriteService;

    public NoteBook save(NoteBook model) {
        // 校验笔记本名称
        boolean existsNoteBookName;
        if (model.isNew()) {
            existsNoteBookName = noteBookRepository.existsByName(model.getName());
        } else {
            existsNoteBookName = noteBookRepository.existsByNameAndIdNot(model.getName(), model.getId());
        }
        if (existsNoteBookName) {
            throw ExceptionHolder.serviceException(E1000002001, model.getName());
        }
        return noteBookRepository.save(model);
    }

    public void delete(UUID id) {
        NoteBook noteBook = noteBookRepository.findById(id)
                .orElseThrow(() -> ExceptionHolder.serviceException(E1000000001, "笔记本-" + id));
        // 查询该笔记本下的所有笔记
        List<Note> notes = noteRepository.findByNoteBook(noteBook);
        if (!CollectionUtils.isEmpty(notes)) {
            // 删除笔记本下的所有笔记
            noteRepository.deleteAllByNoteBook(noteBook);
        }
        // 删除收藏记录
        favoriteService.deleteByNoteBook(noteBook, notes);
        // 删除笔记本
        noteBookRepository.delete(noteBook);
    }
}
